import { defineEventHandler, readBody } from 'h3'

export default defineEventHandler(async (event) => {
  const startTime = new Date()
  try {
    const body = await readBody(event)
    const apiKey = process.env.NUXT_SILICON_API_KEY

    // 打印接收到的完整请求体
    console.log('\n=== Received Request Body ===')
    console.log(JSON.stringify(body, null, 2))
    console.log('=== End Request Body ===\n')

    const model = body.model || 'deepseek-ai/DeepSeek-V3'

    console.log('\n=== AI API Request ===')
    console.log('Time:', startTime.toISOString())
    console.log('Selected Model:', model)
    console.log('Message History:', body.messages)
    console.log('Endpoint:', 'https://api.siliconflow.cn/v1/chat/completions')
    
    const requestParams = {
      model: model,
      messages: body.messages,  // 使用完整的消息历史
      stream: false,
      max_tokens: 1024,
      temperature: 0.7,
      top_p: 0.7,
      top_k: 50,
      frequency_penalty: 0.5,
      n: 1,
      response_format: { type: "text" }
    }

    console.log('Request Params:', JSON.stringify(requestParams, null, 2))

    const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestParams)
    })

    if (!response.ok) {
      const errorData = await response.text()
      throw new Error(`API request failed: ${errorData}`)
    }

    const data = await response.json()
    const endTime = new Date()
    const duration = endTime.getTime() - startTime.getTime()

    console.log('Response Time:', endTime.toISOString())
    console.log('Duration:', duration + 'ms')
    console.log('=== End Request ===\n')

    return data.choices[0].message.content
  } catch (error: any) {
    const endTime = new Date()
    const duration = endTime.getTime() - startTime.getTime()
    
    console.error('\n=== AI API Error ===')
    console.error('Time:', endTime.toISOString())
    console.error('Duration:', duration + 'ms')
    console.error('Error:', error.message)
    console.error('=== End Error ===\n')

    throw createError({
      statusCode: 500,
      message: error.message || 'Failed to process chat request'
    })
  }
}) 